/**
 *
 */
package com.feizhi.common.extractor;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.springframework.stereotype.Component;
import org.xml.sax.ContentHandler;

/**
 * @author shuaqiu
 */
@Component
public class TextExtractor {

    private static final Log LOG = LogFactory.getLog(TextExtractor.class);

    public String extract(final String path) {
        final File file = new File(path);
        return extract(file);
    }

    public String extract(final File file) {
        try {
            final InputStream stream = new FileInputStream(file);
            final String text = extract(stream);

            doClose(stream);

            return text;
        } catch (final FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        }

        return "";
    }

    public String extract(final InputStream stream) {
        final ContentHandler handler = new BodyContentHandler();

        final AutoDetectParser parser = new AutoDetectParser();
        final Metadata metadata = new Metadata();
        try {
            parser.parse(stream, handler, metadata);
            return handler.toString();
        } catch (final Exception e) {
            LOG.error(e.getMessage(), e);
        }

        return "";
    }

    private void doClose(final Closeable stream) {
        try {
            stream.close();
        } catch (final IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
